package com.xiaoyun.config.handlers;

import com.egzosn.pay.common.api.PayMessageHandler;
import com.egzosn.pay.common.api.PayService;
import com.egzosn.pay.common.bean.PayOutMessage;
import com.egzosn.pay.common.exception.PayErrorException;
import com.egzosn.pay.wx.bean.WxPayMessage;
import com.xiaoyun.enums.OrderStatusEnum;
import com.xiaoyun.service.OrderService;
import com.xiaoyun.service.PaymentOrderService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 微信支付回调处理器
 * Created by ZaoSheng on 2016/6/1.
 */
@Component
public class WxPayMessageHandler implements PayMessageHandler<WxPayMessage, PayService> {
    @Autowired
    private PaymentOrderService paymentOrderService;
    @Autowired
    private OrderService orderService;


    @Override
    public PayOutMessage handle(WxPayMessage payMessage, Map<String, Object> context, PayService payService) throws PayErrorException {
        //交易状态
        if ("SUCCESS".equals(payMessage.getPayMessage().get("result_code"))) {
            /////这里进行成功的处理
            Map<String, Object> message = payMessage.getPayMessage();
            String merchantOrderId = (String) message.get("out_trade_no");
            String wxFlowId = (String) message.get("transaction_id");
            Integer payAmount = Integer.valueOf((String) message.get("total_fee"));
            paymentOrderService.updateOrderPaid(merchantOrderId, payAmount);
            //更新订单状态
            orderService.updateOrderStatus(merchantOrderId, OrderStatusEnum.WAIT_DELIVER.type);


            return payService.getPayOutMessage("SUCCESS", "OK");
        }

        return payService.getPayOutMessage("FAIL", "失败");
    }
}
